package jp.millibit.resource
{
	import flash.events.EventDispatcher;


	public class Resource extends EventDispatcher
	{

		private var _uri:String;

		private var _loader:IDataLoader;

		public function Resource(uri:String, loader:IDataLoader)
		{
			_uri = uri;
			_loader = loader;
		}

		public function get uri():String
		{
			return _uri;
		}

		public function get loader():IDataLoader
		{
			return _loader;
		}

		private function dispatch(e:ResourceEvent):void
		{
			dispatchEvent(new ResourceEvent(e.type, e.resource, e.rawData, e.bytesLoaded, e.bytesTotal, e.error));
		}

		public function load(callback:Function = null):void
		{
			var handler:Function = function(e:ResourceEvent):void{
				dispatch(e);

				if (e.type === ResourceEvent.PROGRESS){
					return ;
				}

				_loader.removeEventListener(ResourceEvent.COMPLETE, handler);
				_loader.removeEventListener(ResourceEvent.PROGRESS, handler);
				_loader.removeEventListener(ResourceEvent.FAILURE, handler);

				if (callback != null){
					callback.apply(null, [e.rawData]);
				}
			};

			_loader.addEventListener(ResourceEvent.COMPLETE, handler);
			_loader.addEventListener(ResourceEvent.PROGRESS, handler);
			_loader.addEventListener(ResourceEvent.FAILURE, handler);
			_loader.load(this);
		}
	}
}